import { baseURL } from "./config";
let loginQueue = [];
let isLoginning = false;
const login = () => {
    return new Promise((resolve, reject) => {
        wx.login({
            success(res) {
                if (res.code) {
                    wx.removeStorageSync('wxToken')
			        wx.removeStorageSync('wxUserDetails')
                    wx.request({
                        url: `${baseURL}/api/v2/admin/sponsorAccount/sessionKey`,
                        data: {
                            code: res.code
                        },
                        method: 'get',
                        success: (res) => {
                            wx.setStorageSync('wxToken', res.data.result.token)
                            wx.setStorageSync('wxUserDetails', res.data.result)
                            if (!res.data.result.mobile) {
                                wx.redirectTo({ url: '/pages/authorization/authorization' })
                                reject()
                                return false;
                            } else if (!res.data.result.sponsorList || res.data.result.sponsorList.length == 0) {
                                wx.redirectTo({ url: '/pages/myContent/myContent' })
                                reject()
                                return false;
                            }
                            resolve(res.data.result.token)
                        }
                    })
                } else {
                    reject({
                        msg: '获取code失败',
                        detail: res
                    });
                }
            },
            fail(err) {
                reject(err)
            }
        });
    });
}
export const getToken = (isNeedLogin) => {
    return new Promise((resolve, reject) => {
        if (!isNeedLogin) {
            resolve(wx.getStorageSync('wxToken'));
            return false;
        }
        if (!wx.getStorageSync('wxToken') || !wx.getStorageSync('wxUserDetails').sponsorId) {
            loginQueue.push({ resolve, reject });
            if (!isLoginning) {
                isLoginning = true;
                login().then((toekn) => {
                    isLoginning = false;
                    while (loginQueue.length) {
                        loginQueue.shift().resolve(toekn);
                    }
                }).catch(err => {
                    isLoginning = false;
                    while (loginQueue.length) {
                        loginQueue.shift().reject(err);
                    }
                });
            }
        } else {
            resolve(wx.getStorageSync('wxToken'));
        }
    })
}
